<template>
  <div class="RegisterBox">
    <el-text class="title">注 册 账 号</el-text>
    <el-form :model="RegisterUser" :rules="rules" status-icon ref="ruleForm" class="form">
      <el-form-item prop="username" class="formItem">
        <el-input
            v-model="RegisterUser.username"
            placeholder="请设置用户名"
            size="default"
            maxlength="16"
            :prefix-icon="User"
            class="Input"/>
      </el-form-item>
      <el-form-item prop="password" class="formItem">
        <el-input
            v-model="RegisterUser.password"
            placeholder="请设置密码"
            size="default"
            maxlength="18"
            :prefix-icon="Lock"
            show-password
            class="Input"/>
      </el-form-item>
      <el-form-item prop="pwd2" class="formItem">
        <el-input
            v-model="RegisterUser.pwd2"
            placeholder="请确认密码"
            size="default"
            maxlength="18"
            :prefix-icon="Lock"
            show-password
            class="Input"/>
      </el-form-item>
      <el-form-item prop="email" class="formItem">
        <el-input
            v-model="RegisterUser.email"
            placeholder="请设置邮箱"
            size="default"
            maxlength="24"
            :prefix-icon="Message"
            class="Input"/>
        <el-text class="getCode" @click="getVCode">{{ getVCodeText }}</el-text>
      </el-form-item>
      <el-form-item prop="vcode" class="formItem" v-show="showVCodeInput">
        <el-input
            v-model="RegisterUser.code"
            placeholder="请输入验证码"
            size="default"
            maxlength="10"
            class="Input"/>
      </el-form-item>
      <el-form-item class="formItem">
        <el-select v-model="RegisterUser.gender" placeholder="选择性别" size="default" class="genderSelect">
          <el-option
              v-for="item in genderArray"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-button type="primary" class="RegisterButton" round @click="register">注册</el-button>
  </div>
</template>

<script>
import { User,Search,Lock,Message } from "@element-plus/icons-vue";
export default {
  name: "Register",
  setup(){
    return {
      User,
      Search,
      Lock,
      Message
    }
  },
  data() {
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // \w表示匹配一个单字字符,即字母数字下划线
      const userNameRule = /^[a-zA-Z]\w{4,15}$/;
      if (userNameRule.test(value)) {
        this.$axios
            .get(`${this.$target}/user/username?username=`+value)
            .then(res=>{
              if(res){
                return callback()
              }else{
                return callback(new Error("用户名已存在!"))
              }
            })
      } else {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };

    let validatePwd1 = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 长度在6-18之间,允许字母数字和下划线
      const passwordRule = /^\w{6,18}$/;
      if (passwordRule.test(value)) {
        return callback();
      } else {
        return callback(
            new Error("长度6-18之间,允许字母数字和下划线")
        );
      }
    };

    let validatePwd2 = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请确认密码"));
      }
      if (value == this.RegisterUser.password) {
        return callback();
      } else {
        return callback(
            new Error("两次输入密码不一致!")
        );
      }
    };

    let validateEmail = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入邮箱"));
      }
      const emailRule = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (emailRule.test(value)) {
        this.$axios
            .get(`${this.$target}/user/email?email=`+value)
            .then(res=>{
              if(res){
                return callback()
              }else{
                return callback(new Error("该邮箱已被注册!"))
              }
            })
      }else {
        return callback(new Error("请输入正确的邮箱格式!"));
      }
    };
    return {
      showVCodeInput:false,
      counting:false,
      getVCodeText:"获取验证码",
      RegisterUser:{
        username:"",
        password:"",
        pwd2:"",
        email:"",
        code:"",
        gender:0,
      },
      genderArray:[
        {
          value:0,
          label:"女"
        },
        {
          value:1,
          label:"男"
        },
        {
          value:2,
          label:"保密"
        }
      ],
      rules: {
        username: [{ validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePwd1, trigger: "blur" }],
        pwd2: [{ validator: validatePwd2, trigger: "blur"}],
        email: [{ validator: validateEmail, trigger: "blur"}]
      }
    }
  },
  methods: {
    register(){
      this.$refs["ruleForm"].validate(valid=>{
        if(valid){
          if(this.showVCodeInput){
            this.$axios
                .get(`${this.$target}/user/email/verify?token=`+localStorage.getItem("EmailToken")+`&code=`+this.RegisterUser.code)
                .then(res=>{
                  if(res.data){
                    this.$axios
                        .post(`${this.$target}/user?token=`+localStorage.getItem("EmailToken")+`&code=`+this.RegisterUser.code,JSON.stringify(this.RegisterUser),{
                          headers: {
                            'Content-Type': 'application/json;charset=utf-8'
                          }
                        })
                        .then(res=>{
                          if(res.data){
                            this.notifySucceed("注册成功!")
                            this.$refs["ruleForm"].resetFields();
                          }else{
                            this.notifyError("失败!")
                          }
                        })
                  }else{
                    this.notifyError("验证码错误!")
                  }
                })
          }else{
            this.notifyError("请先获取验证码认证邮箱!")
            return
          }
        }else{
          return
        }
      })
    },
    getVCode(){
      if(!this.counting){
        this.$refs["ruleForm"].validateField('email', valid => {
          if (valid) {
            this.$axios
                .get(`${this.$target}/user/email/code?email=` + this.RegisterUser.email)
                .then(res => {
                  console.log(res.data)
                  this.notifySucceed("成功发送验证码!")
                  this.showVCodeInput = true;
                  localStorage.setItem("EmailToken", res.data)
                  this.counting = true
                  let count = 60
                  let interval = setInterval(() => {
                    if (count >= 10) {
                      this.getVCodeText = "" + count
                    } else if (count != 0) {
                      this.getVCodeText = "0" + count
                    } else {
                      this.getVCodeText = "获取验证码"
                      this.counting = false
                      this.cancelInterval(interval)
                    }
                    count--
                  }, 1000)
                })
          }else{
            this.notifyError("请输入正确的邮箱格式!")
          }
        })
      }else{
        this.notifyError("等待计时结束后重试!")
      }
    },
    cancelInterval(i){
      clearInterval(i)
    }
  }
}
</script>

<style src="@/assets/less/Register.less" scoped lang="less"></style>